import { createRouter, createWebHistory } from 'vue-router'
import {isTokenExpired} from "@/utils/auth";
import Login from "@/views/Login.vue";
import Layout from "@/layout/layout.vue";
import {useAuthStore} from "@/api/auth";
import {toPathFormat} from "@/utils/common";
import {useMenuStore} from "@/stores/menuStore";

// 静态路由 无需权限
const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/',
    name: 'Layout',
    component: Layout,
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('../views/Dashboard.vue'),
        meta: {title : "首页 " , icon : "HomeFilled"}
      },
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
let dynamicRoutesLoaded = false
router.beforeEach(async(to, from, next) => {
  const authStore = useAuthStore()
  const token = authStore.token
  // 如果未登录或 token 过期，跳转到登录页
  if (to.path !== '/login' && to.path !== '/') {
    if (!token) {
     return next('/login')
    }

    // 过期则清除 token 跳转回登录页
    if (isTokenExpired(token)) {
      console.log('token 过期 退出登录')
      // 登出 删除 token
      authStore.logout()
      return next('/login')
    }

    // 刷新 token
    const playload = parseJwt(token)
    let expire = playload.exp
    const now = Date.now() / 1000
    if (expire - now < 3600) {
      // 续期
      await authStore.getNewToken()
    }

    // 动态生成路由
    if (!dynamicRoutesLoaded) {
      await generateRoutesFromMenu()
      dynamicRoutesLoaded = true
      return next({ ...to, replace: true })
    }
  }
  next()
})

// 解析 Jwt
function parseJwt(token) {
  try {
    return  JSON.parse(atob(token.split('.')[1])) // 解析 JWT payload
  }catch (error) {
    console.error('Invalid token:', error)
    return null
  }
}

// 后端返回的菜单结构（可带 path、component、children 等）
export async function generateRoutesFromMenu() {
  const menuStore = useMenuStore()
  
  // 先尝试使用现有数据
  let menuTree = menuStore.getMenuTree
  
  // 如果数据为空，再触发获取
  if (!menuTree || menuTree.length === 0) {
    // fixme 这里要改成获取当前角色下的菜单列表
    await menuStore.fetchMenu()
    menuTree = menuStore.getMenuTree
  }
  
  // 添加每个路由到路由表
  const asyncRoutes = buildRoutesFromMenu(menuTree)
  asyncRoutes.forEach(route => {
    safeAddRoute('Layout', route) // 确保 'Layout' 是已存在的父路由
  })
}

// 递归构建前端路由
//
// 如果是 单级菜单名（如 menu），默认加载 views/${component}/${component}.vue
// 如果是 多级路径（如 menu/list 或 MenuList），默认加载 views/${component}/index.vue
function buildRoutesFromMenu(menuList) {
  return menuList
      .filter(item => !!item.component || item.children?.length > 0)
      .map(item => {
        // 纯父级菜单（无 component，有 children）
        if (!item.component && item.children?.length > 0) {
          return {
            path: item.path || `/${item.name}`, // 给父级一个默认路径
            name: item.name,
            meta: {
              title: item.name,
              icon: item.icon,
              permission: item.permission
            },
            children: buildRoutesFromMenu(item.children)
          }
        }

        // 根据 component 推导路径
        const component = toPathFormat(item.component)
        const componentName = component.trim().replace(/^\/+|\/+$/g, '') // 去除前后斜杠

        // 根据 component 类型推导路径
        let routePath = '/' + componentName
        // 生成唯一的 name（驼峰命名）
        const route = {
          path: routePath,
          name: item.name,
          meta: {
            title: item.title || item.name,
            icon: item.icon,
            permission: item.permission
          },
          component: () =>
            import(`@/views/${componentName}/index.vue`).catch(err => {
              console.error(`组件加载失败: ${componentName}`, err)
              return import('@/views/dashboard.vue')
            })
        }
        console.log('加载组件:', `@/views/${componentName}/index.vue`)

        if (item.children && item.children.length > 0) {
          route.children = buildRoutesFromMenu(item.children)
        }
        console.log(`路由: ${componentName} → 路径: ${routePath}`)
        return route
      })
}

function safeAddRoute(parentName, route) {
  try {
    console.log(route)
    router.addRoute(parentName, route)
    return true
  } catch (err) {
    console.error('添加路由失败:', err)
    return false
  }
}


export default router